'use client'

import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  IconActivity,
  IconUsers,
  IconBed,
  IconAlertTriangle,
  IconTrendingUp,
  IconTrendingDown,
  IconMaximize,
  IconMinimize,
  IconRefresh,
  IconChartBar,
  IconMap,
  IconClock,
  IconHeart,
  IconShield,
  IconTarget,
  IconBolt,
  IconGauge
} from '@tabler/icons-react'
import * as echarts from 'echarts'
import * as THREE from 'three'
import { HospitalMapViewer, HospitalMapViewerRef, POIData, StoreData } from '@/components/HospitalMapViewer'
import usePOIIntentStore from '@/stores/poiIntentStore'
import { HospitalSiteManager } from '@/components/HospitalSiteManager'
import { Input } from '@/components/ui/input'
import { useI18n } from '@jjk/guo'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { toast } from 'sonner'
import { config, AMAP_KEY, DEFAULT_CENTER, DEFAULT_ZOOM } from '@/lib/config'
import { timeUtils } from '@/lib/realData'
import { staticDataService } from '@/lib/staticData'
import { clientDataService } from '@/lib/clientDataService'
import { EmergencyEvent, emergencyService } from '@/lib/emergencyEvents'
import { poiCatalog } from '@/lib/poiCatalog'
import { hospitalDB } from '@/lib/indexedDB'
import EmergencyPanel from '@/components/EmergencyPanel'

interface MetricData {
  value: number
  trend: number
  status: 'excellent' | 'good' | 'warning' | 'critical'
  lastUpdate: Date
}

interface ChartData {
  labels: string[]
  datasets: {
    label: string
    data: number[]
    color: string
  }[]
}

interface HospitalSite {
  id: string
  name: string
  center: [number, number]
  zoom: number
  address?: string
  district?: string
  city?: string
  province?: string
}

interface VisualizationDashboardProps {
  screenSize?: 'sm' | 'md' | 'lg' | 'xl' | '2xl'
  windowSize?: { width: number; height: number }
  isFullscreen?: boolean
  isMobile?: boolean
  isTablet?: boolean
  scaleFactor?: number
  baseFontSize?: number
}

export default function VisualizationDashboard({
  screenSize = 'lg',
  windowSize = { width: 1920, height: 1080 },
  isFullscreen: externalFullscreen = false,
  isMobile = false,
  isTablet = false,
  scaleFactor = 1,
  baseFontSize = 16
}: VisualizationDashboardProps) {
  const { t, locale } = useI18n()
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [lastUpdate, setLastUpdate] = useState<string>('')
  const [chartsInitialized, setChartsInitialized] = useState<boolean>(false)
  const [metrics, setMetrics] = useState<Record<string, MetricData>>({})
  const [isNarrowScreen, setIsNarrowScreen] = useState(false)
  const [realTimeData, setRealTimeData] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isDataRefreshing, setIsDataRefreshing] = useState(false)



  // 性能优化：缓存图表配置
  const chartConfigCache = useRef(new Map())
  const mapViewerRef = useRef<HospitalMapViewerRef>(null)
  // 在线用户面板拖拽位置（默认右下）
  const [userPanelPos, setUserPanelPos] = useState<{ x: number, y: number }>({ x: 0, y: 0 })
  const userPanelRef = useRef<HTMLDivElement>(null)
  const poiIntent = usePOIIntentStore(s => s.intent)
  const consumePOIIntent = usePOIIntentStore(s => s.consumeIntent)

  // 清理缓存的函数
  const clearChartCache = useCallback(() => {
    chartConfigCache.current.clear()
  }, [])

  // 这个useEffect会在所有函数定义之后添加

  useEffect(() => {
    // 初始化到右下角，留出边距
    const init = () => {
      const panelWidth = 288 // 估算宽度 w-72
      const panelHeight = 320 // 估算高度 max-h-80
      const x = Math.max(16, window.innerWidth - panelWidth - 16)
      const y = Math.max(80, window.innerHeight - panelHeight - 16)
      setUserPanelPos({ x, y })
    }
    init()
    window.addEventListener('resize', init)
    return () => window.removeEventListener('resize', init)
  }, [])

  // 地图管理相关状态
  const [sites, setSites] = useState<HospitalSite[]>([])
  const [currentSiteId, setCurrentSiteId] = useState<string>('')
  const [currentSite, setCurrentSite] = useState<HospitalSite | null>(null)
  const [selectedPosition, setSelectedPosition] = useState<[number, number, number] | null>(null)
  const [mapDisplayMode, setMapDisplayMode] = useState<'overview' | 'departments' | 'equipment' | 'alerts'>('overview')
  const [pois, setPOIs] = useState<POIData[]>([])
  const [stores, setStores] = useState<StoreData[]>([])
  const [emergencies, setEmergencies] = useState<EmergencyEvent[]>([])

  // POI 添加相关状态
  const [selectedModel, setSelectedModel] = useState<{ object: THREE.Object3D, point: THREE.Vector3 } | null>(null)
  const [showAddPOI, setShowAddPOI] = useState(false)
  const [poiForm, setPOIForm] = useState({
    name: '',
    type: 'department' as POIData['type'],
    floor: 'L1',
    description: ''
  })

  // 拖拽在线用户面板
  const startDragUserPanel = useCallback((e: React.MouseEvent) => {
    e.preventDefault()
    const startX = e.clientX
    const startY = e.clientY
    const startPos = { ...userPanelPos }

    const onMove = (ev: MouseEvent) => {
      const dx = ev.clientX - startX
      const dy = ev.clientY - startY
      const panelWidth = (userPanelRef.current?.offsetWidth || 288)
      const panelHeight = (userPanelRef.current?.offsetHeight || 240)
      const minX = 16
      const minY = 16
      const maxX = Math.max(minX, window.innerWidth - panelWidth - 16)
      const maxY = Math.max(minY, window.innerHeight - panelHeight - 16)
      const nx = Math.min(maxX, Math.max(minX, startPos.x + dx))
      const ny = Math.min(maxY, Math.max(minY, startPos.y + dy))
      setUserPanelPos({ x: nx, y: ny })
    }

    const onUp = () => {
      window.removeEventListener('mousemove', onMove)
      window.removeEventListener('mouseup', onUp)
    }

    window.addEventListener('mousemove', onMove)
    window.addEventListener('mouseup', onUp)
  }, [userPanelPos])

  // 响应其他页面设置的 POI 意图：
  useEffect(() => {
    if (!poiIntent) return
    const intent = consumePOIIntent()
    if (!intent) return
    // 1) 定位
    if (intent.center && mapViewerRef.current) {
      mapViewerRef.current.flyTo(intent.center, intent.zoom || 18)
    }
    // 2) 显示 POI
    if (intent.pois && intent.pois.length > 0) {
      // 先清空已有
      mapViewerRef.current?.clearAllPOIs?.()
      setPOIs(intent.pois)
      intent.pois.forEach(p => mapViewerRef.current?.addPOI?.(p))
      toast.success(`已加载 ${intent.pois.length} 个目标点位`)
      setMapDisplayMode('departments')
    }
  }, [poiIntent])

  // --- AI Advisor integration ---
  const [showAdvisor, setShowAdvisor] = useState(false)

  // 地图点击处理函数
  const handleMapClick = useCallback((lngLat: [number, number]) => {
    console.log('🎯 VisualizationDashboard 收到地图点击:', lngLat)
    console.log('🔄 设置 selectedPosition...')
    setSelectedPosition([lngLat[0], lngLat[1], 0])
    setSelectedModel(null)
    console.log('✅ selectedPosition 状态已更新')
    toast.success(`地图坐标: ${lngLat[0].toFixed(6)}, ${lngLat[1].toFixed(6)}`)
  }, [])

  const handleModelClick = useCallback((object: THREE.Object3D, point: THREE.Vector3) => {
    console.log('🎯 VisualizationDashboard 收到模型点击:', object.name, point)
    setSelectedModel({ object, point })
    setSelectedPosition(null)
    if (object.name === 'floor') {
      toast.success('点击地板 - 可添加设施点位')
    } else {
      toast.success(`点击建筑 - 可添加科室 (${object.name})`)
    }
  }, [])

  // 初始化默认站点
  useEffect(() => {
    const defaultSite: HospitalSite = {
      id: 'default',
      name: '默认医院',
      center: DEFAULT_CENTER,
      zoom: DEFAULT_ZOOM,
      address: '浙江省杭州市'
    }
    setSites([defaultSite])
    setCurrentSiteId('default')
    setCurrentSite(defaultSite)
  }, [])

  // 初始化突发事件系统
  useEffect(() => {
    const activeEvents = emergencyService.getActiveEmergencies()
    setEmergencies(activeEvents)

    const unsubscribe = emergencyService.addListener((events) => {
      setEmergencies(events)
    })

    return () => {
      unsubscribe()
    }
  }, [])

  // 获取真实医院POI数据
  const searchRealHospitalPOIs = useCallback(async (hospitalName: string) => {
    if (!mapViewerRef.current) return

    try {
      // 使用高德地图POI搜索API
      const AMap = (window as any).AMap
      if (!AMap) {
        toast.error('地图未加载完成')
        return
      }

      // 检查并加载 PlaceSearch 插件
      if (!AMap.PlaceSearch) {
        try {
          await new Promise<void>((resolve, reject) => {
            AMap.plugin('AMap.PlaceSearch', () => {
              if (AMap.PlaceSearch) {
                resolve()
              } else {
                reject(new Error('PlaceSearch 插件加载失败'))
              }
            })
          })
        } catch (error) {
          console.error('加载 PlaceSearch 插件失败:', error)
          toast.error('地图搜索功能加载失败')
          return
        }
      }

      const poiSearcher = new AMap.PlaceSearch({
        type: '医疗保健服务', // 医院类别
        pageSize: 50,
        pageIndex: 1,
        city: '杭州', // 根据需要修改城市
        extensions: 'all'
      })

      return new Promise((resolve, reject) => {
        poiSearcher.search(hospitalName, (status: string, result: any) => {
          console.log('POI搜索返回状态:', status, '结果:', result)

          if (status === 'complete' && result.info === 'OK') {
            const realPOIs: POIData[] = result.poiList.pois.map((poi: any, index: number) => ({
              id: `real_poi_${poi.id}`,
              name: poi.name,
              type: 'department' as const,
              position: [poi.location.lng, poi.location.lat],
              floor: 'L1',
              description: `地址: ${poi.address || '未知'}\n电话: ${poi.tel || '未知'}`,
              metadata: {
                address: poi.address,
                phone: poi.tel,
                category: poi.type,
                businessArea: poi.businessArea,
                cityCode: poi.citycode,
                source: 'amap_poi'
              }
            }))

            // 通过地图组件添加POI（地图组件会自动管理内部状态）
            realPOIs.forEach(poi => {
              mapViewerRef.current?.addPOI?.(poi)
            })
            // 同步Dashboard状态，但不会影响地图组件的内部状态
            setPOIs(realPOIs)
            toast.success(`已替换为 ${realPOIs.length} 个真实POI点位`)
            resolve(realPOIs)
          } else {
            // 如果是API Key问题，使用模拟数据
            if (result === 'USERKEY_PLAT_NOMATCH' || (typeof result === 'string' && result.includes('USERKEY'))) {
              console.warn('检测到API Key问题，使用模拟医院POI数据')

              // 生成模拟的医院POI数据
              const mockPOIs: POIData[] = [
                {
                  id: 'mock_hospital_1',
                  name: `${hospitalName}示例医院`,
                  type: 'department' as const,
                  position: [120.1551, 30.2741],
                  floor: 'L1',
                  description: '地址: 模拟地址\n电话: 模拟电话',
                  metadata: { source: 'mock_poi' }
                },
                {
                  id: 'mock_hospital_2',
                  name: `${hospitalName}分院`,
                  type: 'department' as const,
                  position: [120.1561, 30.2751],
                  floor: 'L1',
                  description: '地址: 模拟地址2\n电话: 模拟电话2',
                  metadata: { source: 'mock_poi' }
                }
              ]

              // 添加模拟POI
              mockPOIs.forEach(poi => {
                mapViewerRef.current?.addPOI?.(poi)
              })
              setPOIs(mockPOIs)

              toast.info(`已加载 ${mockPOIs.length} 个模拟医院POI（API Key需配置）`)
              resolve(mockPOIs)
            } else {
              console.error('POI搜索失败 - 状态:', status, '结果:', result)
              toast.error('搜索POI失败')
              reject(new Error('POI搜索失败'))
            }
          }
        })
      })
    } catch (error) {
      console.error('搜索真实POI失败:', error)
      toast.error('搜索真实POI失败')
    }
  }, [])

  // 根据医院坐标搜索周边科室
  const searchNearbyDepartments = useCallback(async (center: [number, number], radius: number = 1000) => {
    try {
      const AMap = (window as any).AMap
      if (!AMap) return

      // 检查并加载 PlaceSearch 插件
      if (!AMap.PlaceSearch) {
        try {
          await new Promise<void>((resolve, reject) => {
            AMap.plugin('AMap.PlaceSearch', () => {
              if (AMap.PlaceSearch) {
                resolve()
              } else {
                reject(new Error('PlaceSearch 插件加载失败'))
              }
            })
          })
        } catch (error) {
          console.error('加载 PlaceSearch 插件失败:', error)
          toast.error('地图搜索功能加载失败')
          return
        }
      }

      const nearbySearcher = new AMap.PlaceSearch({
        type: '医疗保健服务|科教文化服务',
        pageSize: 50,
        extensions: 'all'
      })

      return new Promise((resolve, reject) => {
        nearbySearcher.searchNearBy('医院|科室|诊所', new AMap.LngLat(center[0], center[1]), radius, (status: string, result: any) => {
          console.log('周边搜索返回状态:', status, '结果:', result)

          if (status === 'complete' && result.info === 'OK') {
            // 检查结果结构
            if (!result.poiList || !result.poiList.pois || !Array.isArray(result.poiList.pois)) {
              console.warn('周边搜索结果结构异常:', result)
              toast.info('周边暂无相关科室数据')
              resolve([])
              return
            }

            const nearbyPOIs: POIData[] = result.poiList.pois
              .filter((poi: any) => poi.name.includes('科') || poi.name.includes('部门') || poi.name.includes('诊'))
              .map((poi: any) => ({
                id: `nearby_${poi.id}`,
                name: poi.name,
                type: 'department' as const,
                position: [poi.location.lng, poi.location.lat],
                floor: 'L1',
                description: `距离: ${poi.distance}米\n地址: ${poi.address || '未知'}`,
                metadata: {
                  distance: poi.distance,
                  address: poi.address,
                  phone: poi.tel,
                  source: 'amap_nearby'
                }
              }))

            console.log('找到周边科室:', nearbyPOIs.length, '个')

            // 通过地图组件添加POI（地图组件会自动管理内部状态）
            nearbyPOIs.forEach(poi => {
              mapViewerRef.current?.addPOI?.(poi)
            })
            // 同步Dashboard状态，但不会影响地图组件的内部状态
            setPOIs(nearbyPOIs)

            if (nearbyPOIs.length > 0) {
              toast.success(`已替换为 ${nearbyPOIs.length} 个周边科室`)
            } else {
              toast.info('周边暂无相关科室，请尝试扩大搜索范围')
            }
            resolve(nearbyPOIs)
          } else {
            console.error('周边搜索失败 - 状态:', status, '信息:', result?.info, '完整结果:', result)

            // 如果是API Key问题，使用模拟数据
            if (result === 'USERKEY_PLAT_NOMATCH' || (typeof result === 'string' && result.includes('USERKEY'))) {
              console.warn('检测到API Key问题，使用模拟周边科室数据')

              // 生成模拟的周边科室数据
              const mockNearbyPOIs: POIData[] = [
                {
                  id: 'mock_nearby_1',
                  name: '急诊科',
                  type: 'department' as const,
                  position: [center[0] + 0.001, center[1] + 0.001],
                  floor: 'L1',
                  description: '距离: 约100米\n地址: 模拟地址',
                  metadata: { distance: 100, source: 'mock_nearby' }
                },
                {
                  id: 'mock_nearby_2',
                  name: '内科诊室',
                  type: 'department' as const,
                  position: [center[0] - 0.001, center[1] + 0.001],
                  floor: 'L2',
                  description: '距离: 约150米\n地址: 模拟地址',
                  metadata: { distance: 150, source: 'mock_nearby' }
                },
                {
                  id: 'mock_nearby_3',
                  name: '外科门诊',
                  type: 'department' as const,
                  position: [center[0] + 0.001, center[1] - 0.001],
                  floor: 'L3',
                  description: '距离: 约200米\n地址: 模拟地址',
                  metadata: { distance: 200, source: 'mock_nearby' }
                }
              ]

              // 添加模拟POI
              mockNearbyPOIs.forEach(poi => {
                mapViewerRef.current?.addPOI?.(poi)
              })
              setPOIs(mockNearbyPOIs)

              toast.info(`已加载 ${mockNearbyPOIs.length} 个模拟周边科室（API Key需配置）`)
              resolve(mockNearbyPOIs)
            } else {
              const errorMsg = result?.info || '未知错误'
              reject(new Error(`周边搜索失败: ${errorMsg} (状态: ${status})`))
            }
          }
        })
      })
    } catch (error) {
      console.error('搜索周边科室失败:', error)
      toast.error(`搜索周边科室失败: ${error instanceof Error ? error.message : '未知错误'}`)
      return []
    }
  }, [])

  // 响应式工具函数
  const getResponsiveCardPadding = () => {
    return screenSize === 'sm' ? 'p-3' : screenSize === 'md' ? 'p-4' : 'p-6'
  }

  const getResponsiveFontSize = (base: string) => {
    switch (base) {
      case 'title':
        return screenSize === 'sm' ? 'text-lg' : screenSize === 'md' ? 'text-xl' : 'text-2xl'
      case 'metric':
        return screenSize === 'sm' ? 'text-xl' : screenSize === 'md' ? 'text-2xl' : 'text-3xl'
      case 'large-metric':
        return screenSize === 'sm' ? 'text-2xl' : screenSize === 'md' ? 'text-3xl' : 'text-4xl'
      case 'label':
        return screenSize === 'sm' ? 'text-xs' : 'text-sm'
      default:
        return base
    }
  }

  const getResponsiveGridCols = () => {
    switch (screenSize) {
      case 'sm': return 'grid-cols-1'
      case 'md': return 'grid-cols-2'
      case 'lg': return 'grid-cols-3'
      case 'xl': return 'grid-cols-3'
      case '2xl': return 'grid-cols-3'
      default: return 'grid-cols-3'
    }
  }

  const getChartHeight = () => {
    if (isMobile) {
      return '250px'
    } else if (isTablet) {
      return '350px'
    }

    switch (screenSize) {
      case 'sm': return '300px'
      case 'md': return '400px'
      case 'lg': return '450px'
      case 'xl': return '500px'
      case '2xl': return '550px'
      default: return '450px'
    }
  }

  const getMobileOptimizedCardSize = () => {
    const scaledWidth = Math.round(280 * scaleFactor) // Base 280px
    const scaledHeight = Math.round(200 * scaleFactor) // Base 200px

    if (isMobile) {
      return {
        width: 'w-48 sm:w-52',
        height: 'h-32 sm:h-36',
        padding: 'p-2',
        titleSize: 'text-xs',
        iconSize: 'w-3 h-3'
      }
    } else if (isTablet) {
      return {
        width: 'w-56 sm:w-60',
        height: 'h-40 sm:h-44',
        padding: 'p-3',
        titleSize: 'text-sm',
        iconSize: 'w-4 h-4'
      }
    }

    // 动态计算卡片大小
    const widthClass = scaledWidth <= 224 ? 'w-56' : scaledWidth <= 256 ? 'w-64' : scaledWidth <= 288 ? 'w-72' : 'w-80'
    const heightClass = scaledHeight <= 192 ? 'h-48' : scaledHeight <= 208 ? 'h-52' : 'h-56'

    return {
      width: `${widthClass} sm:w-64 lg:w-72 xl:w-80`,
      height: heightClass,
      padding: 'p-4',
      titleSize: getScaledFontSize('text-base'),
      iconSize: getScaledIconSize('w-4 h-4')
    }
  }

  const getScaledFontSize = (baseClass: string) => {
    const sizeMap: Record<string, number> = {
      'text-xs': 12,
      'text-sm': 14,
      'text-base': 16,
      'text-lg': 18,
      'text-xl': 20,
      'text-2xl': 24
    }

    const baseSize = sizeMap[baseClass] || 16
    const scaledSize = Math.round(baseSize * scaleFactor)

    if (scaledSize <= 12) return 'text-xs'
    if (scaledSize <= 14) return 'text-sm'
    if (scaledSize <= 16) return 'text-base'
    if (scaledSize <= 18) return 'text-lg'
    if (scaledSize <= 20) return 'text-xl'
    return 'text-2xl'
  }

  const getScaledIconSize = (baseClass: string) => {
    const sizeMatch = baseClass.match(/w-(\d+)\s+h-(\d+)/)
    if (!sizeMatch) return baseClass

    const baseSize = parseInt(sizeMatch[1])
    const scaledSize = Math.round(baseSize * scaleFactor)
    const clampedSize = Math.max(3, Math.min(8, scaledSize))

    return `w-${clampedSize} h-${clampedSize}`
  }

  // 大屏幕图表引用
  const leftChartRef = useRef<HTMLDivElement>(null)
  const deviceRadarRef = useRef<HTMLDivElement>(null)
  const patientFlowPieRef = useRef<HTMLDivElement>(null)




  // 大屏幕图表实例
  const leftChartInstance = useRef<echarts.ECharts | null>(null)
  const deviceRadarInstance = useRef<echarts.ECharts | null>(null)
  const patientFlowPieInstance = useRef<echarts.ECharts | null>(null)



  // 处理站点变化
  const handleSitesChange = useCallback((newSites: HospitalSite[]) => {
    setSites(newSites)
    // 保存到本地存储
    localStorage.setItem('hospital_sites', JSON.stringify(newSites))
  }, [])

  // 处理站点选择
  const handleSiteSelect = useCallback((siteId: string) => {
    const isCurrentSite = currentSiteId === siteId
    setCurrentSiteId(siteId)
    const site = sites.find(s => s.id === siteId)

    if (site) {
      setCurrentSite(site)
      // 保存当前选中的站点
      localStorage.setItem('current_site_id', siteId)

      if (!isCurrentSite) {
        // 只有在真正切换站点时才清除状态，避免重复点击同一站点清除定位高亮
        setSelectedPosition(null)

        // 清除地图中的选中状态和高亮效果
        if (mapViewerRef.current) {
          mapViewerRef.current.clearSelectedPOI()
          mapViewerRef.current.clearHighlight()
        }

        console.log('站点切换:', { from: currentSiteId, to: siteId, site })
      } else {
        console.log('重新选择当前站点:', { siteId, site })
        // 重新选择当前站点，创建定位高亮效果
        if (mapViewerRef.current) {
          setTimeout(() => {
            mapViewerRef.current?.flyTo(site.center, site.zoom)
          }, 100)
        }
      }
    }
  }, [sites, currentSiteId])

  // 地图点击事件处理已在前面定义

  // 获取真实数据
  const loadRealData = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setIsDataRefreshing(true)
      } else {
        setIsLoading(true)
      }

      // 已通过 setIsLoading / setIsDataRefreshing 管理加载状态

      // 尝试从 API 获取数据
      const data = await clientDataService.getAllRealTimeData()
      setRealTimeData(data)

      // 更新数据源状态

      // 更新指标数据
      const newMetrics: Record<string, MetricData> = {
        bedUtilization: {
          value: data.kpis.bedUtilization?.value || 0,
          trend: data.kpis.bedUtilization?.trend || 0,
          status: (data.kpis.bedUtilization?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.bedUtilization?.timestamp || new Date()
        },
        patientFlow: {
          value: data.kpis.patientFlow?.value || 0,
          trend: data.kpis.patientFlow?.trend || 0,
          status: (data.kpis.patientFlow?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.patientFlow?.timestamp || new Date()
        },
        deviceEfficiency: {
          value: data.kpis.equipmentEfficiency?.value || 0,
          trend: data.kpis.equipmentEfficiency?.trend || 0,
          status: (data.kpis.equipmentEfficiency?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.equipmentEfficiency?.timestamp || new Date()
        },
        satisfaction: {
          value: data.kpis.patientSatisfaction?.value || 0,
          trend: data.kpis.patientSatisfaction?.trend || 0,
          status: (data.kpis.patientSatisfaction?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.patientSatisfaction?.timestamp || new Date()
        },
        emergencyResponse: {
          value: data.kpis.emergencyResponse?.value || 0,
          trend: data.kpis.emergencyResponse?.trend || 0,
          status: (data.kpis.emergencyResponse?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.emergencyResponse?.timestamp || new Date()
        },
        resourceUtilization: {
          value: data.kpis.averageWaitTime?.value || 0,
          trend: data.kpis.averageWaitTime?.trend || 0,
          status: (data.kpis.averageWaitTime?.status as 'excellent' | 'good' | 'warning' | 'critical') || 'good',
          lastUpdate: data.kpis.averageWaitTime?.timestamp || new Date()
        }
      }

      // 添加一些随机变化以模拟实时更新
      Object.keys(newMetrics).forEach(key => {
        const metric = newMetrics[key]
        // 移除随机数，保持固定值
        // const change = (Math.random() - 0.5) * 4 // -2 到 +2 的变化
        // metric.value = Math.max(0, Math.min(100, metric.value + change))
        // metric.trend = Math.round((Math.random() - 0.5) * 200) / 10
        metric.status = metric.value >= 95 ? 'excellent' :
          metric.value >= 85 ? 'good' :
            metric.value >= 70 ? 'warning' : 'critical'
        metric.lastUpdate = new Date()
      })

      setMetrics(newMetrics)
      setLastUpdate(timeUtils.formatTime(new Date()))

      // 更新图表数据
      updateLeftChart()

      // 数据加载完成
      setIsLoading(false)
      setIsDataRefreshing(false)

      // 更新加载状态


    } catch (error) {
      console.error('从 API 获取数据失败，使用模拟数据:', error)

      // 更新数据源状态为错误

      // 回退到静态模拟数据（避免随机数生成）
      const data = staticDataService.getAllRealTimeData()
      setRealTimeData(data)

      // 更新数据源状态为模拟数据

      // 更新指标数据
      const newMetrics: Record<string, MetricData> = {
        bedUtilization: {
          ...data.kpis.bedUtilization,
          status: data.kpis.bedUtilization.status as 'excellent' | 'good' | 'warning' | 'critical'
        },
        patientFlow: {
          ...data.kpis.patientFlow,
          status: data.kpis.patientFlow.status as 'excellent' | 'good' | 'warning' | 'critical'
        },
        deviceEfficiency: {
          ...data.kpis.equipmentEfficiency,
          status: data.kpis.equipmentEfficiency.status as 'excellent' | 'good' | 'warning' | 'critical'
        },
        satisfaction: {
          ...data.kpis.patientSatisfaction,
          status: data.kpis.patientSatisfaction.status as 'excellent' | 'good' | 'warning' | 'critical'
        },
        emergencyResponse: {
          ...data.kpis.emergencyResponse,
          status: data.kpis.emergencyResponse.status as 'excellent' | 'good' | 'warning' | 'critical'
        },
        resourceUtilization: {
          ...data.kpis.averageWaitTime,
          status: data.kpis.averageWaitTime.status as 'excellent' | 'good' | 'warning' | 'critical'
        }
      }
      Object.keys(newMetrics).forEach(key => {
        const metric = newMetrics[key]
        // 移除随机数，保持固定值
        // const change = (Math.random() - 0.5) * 4 // -2 到 +2 的变化
        // metric.value = Math.max(0, Math.min(100, metric.value + change))
        // metric.trend = Math.round((Math.random() - 0.5) * 200) / 10
        metric.status = metric.value >= 95 ? 'excellent' :
          metric.value >= 85 ? 'good' :
            metric.value >= 70 ? 'warning' : 'critical'
        metric.lastUpdate = new Date()
      })
      setMetrics(newMetrics)
      setLastUpdate(timeUtils.formatTime(new Date()))

      // 更新图表数据
      updateLeftChart()

      // 模拟数据加载完成
      setIsLoading(false)
      setIsDataRefreshing(false)

      // 更新加载状态

    }
  }

  // 初始化图表
  const initCharts = () => {
    // 使用 requestAnimationFrame 确保DOM元素已经渲染
    requestAnimationFrame(() => {
      let initialized = false

      // 初始化大屏幕图表
      if (leftChartRef.current && !leftChartInstance.current) {
        leftChartInstance.current = echarts.init(leftChartRef.current)
        initialized = true
      }
      if (deviceRadarRef.current && !deviceRadarInstance.current) {
        deviceRadarInstance.current = echarts.init(deviceRadarRef.current)
        initialized = true
      }
      if (patientFlowPieRef.current && !patientFlowPieInstance.current) {
        patientFlowPieInstance.current = echarts.init(patientFlowPieRef.current)
        initialized = true
      }



      if (initialized) {
        setChartsInitialized(true)
      }
    })
  }

  // 防抖函数
  const debounce = useCallback(<T extends unknown[]>(func: (...args: T) => void, delay: number) => {
    let timeoutId: NodeJS.Timeout
    return (...args: T) => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => func(...args), delay)
    }
  }, [])

  // 获取缩放后的字体大小 - 使用useMemo优化
  const getScaledFontSizeNumber = useMemo(() => (baseSize: number) => {
    return Math.round(baseSize * scaleFactor)
  }, [scaleFactor])

  // 生成实时监控图表配置
  const generateRealTimeChartOption = useCallback(() => {
    const now = new Date()
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()

    // 生成完整的24小时时间轴
    const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)

    // 初始化数据数组，未来时间用null表示
    const patientFlow = new Array(24).fill(null)
    const deviceUsage = new Array(24).fill(null)
    const emergencyCalls = new Array(24).fill(null)

    // 使用固定的种子生成历史数据，确保历史数据不变
    const seed = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)) // 按天计算种子
    const seededRandom = (index: number) => {
      const x = Math.sin(seed + index) * 10000
      return x - Math.floor(x)
    }

    // 只填充当前时间之前的数据
    for (let i = 0; i <= currentHour; i++) {
      // 根据时间段生成合理的数据，使用固定种子确保历史数据不变
      let basePatientFlow, baseDeviceUsage, baseEmergencyCalls

      if (i >= 6 && i <= 10) {
        // 上午高峰
        basePatientFlow = 80 + seededRandom(i) * 40
        baseDeviceUsage = 85 + seededRandom(i + 100) * 15
        baseEmergencyCalls = 8 + seededRandom(i + 200) * 7
      } else if (i >= 11 && i <= 14) {
        // 中午时段
        basePatientFlow = 60 + seededRandom(i) * 30
        baseDeviceUsage = 75 + seededRandom(i + 100) * 20
        baseEmergencyCalls = 5 + seededRandom(i + 200) * 5
      } else if (i >= 15 && i <= 19) {
        // 下午高峰
        basePatientFlow = 90 + seededRandom(i) * 50
        baseDeviceUsage = 90 + seededRandom(i + 100) * 10
        baseEmergencyCalls = 10 + seededRandom(i + 200) * 8
      } else if (i >= 20 && i <= 23) {
        // 晚上时段
        basePatientFlow = 40 + seededRandom(i) * 30
        baseDeviceUsage = 70 + seededRandom(i + 100) * 20
        baseEmergencyCalls = 3 + seededRandom(i + 200) * 4
      } else {
        // 深夜时段 (0-5点)
        basePatientFlow = 20 + seededRandom(i) * 20
        baseDeviceUsage = 60 + seededRandom(i + 100) * 15
        baseEmergencyCalls = 2 + seededRandom(i + 200) * 3
      }

      patientFlow[i] = Math.floor(basePatientFlow)
      deviceUsage[i] = Math.floor(baseDeviceUsage)
      emergencyCalls[i] = Math.floor(baseEmergencyCalls)
    }

    // 如果是当前小时，添加当前分钟的数据点（只有这个数据点会实时变化）
    if (currentMinute > 0) {
      // 在时间轴中插入当前分钟
      hours.splice(currentHour + 1, 0, `${currentHour}:${currentMinute.toString().padStart(2, '0')}`)

      // 在数据数组中插入当前分钟的数据（使用当前时间作为随机种子，确保实时变化）
      const currentSeed = Math.floor(now.getTime() / (1000 * 60)) // 按分钟计算种子
      const currentRandom = (offset: number) => {
        const x = Math.sin(currentSeed + offset) * 10000
        return x - Math.floor(x)
      }

      const currentPatientFlow = patientFlow[currentHour] + Math.floor((currentRandom(0) - 0.5) * 10)
      const currentDeviceUsage = deviceUsage[currentHour] + Math.floor((currentRandom(1) - 0.5) * 5)
      const currentEmergencyCalls = emergencyCalls[currentHour] + Math.floor((currentRandom(2) - 0.5) * 2)

      patientFlow.splice(currentHour + 1, 0, Math.max(0, currentPatientFlow))
      deviceUsage.splice(currentHour + 1, 0, Math.max(0, Math.min(100, currentDeviceUsage)))
      emergencyCalls.splice(currentHour + 1, 0, Math.max(0, currentEmergencyCalls))
    }

    return {
      backgroundColor: 'transparent',
      title: {
        text: locale === 'en'
          ? `24-Hour Real-time Monitoring (Current Time: ${currentHour}:${currentMinute.toString().padStart(2, '0')})`
          : `24小时实时监控 (当前时间: ${currentHour}:${currentMinute.toString().padStart(2, '0')})`,
        textStyle: {
          color: '#ffffff',
          fontSize: 16,
          fontWeight: 'bold'
        },
        left: 'center',
        top: 2
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: 'rgba(0, 0, 0, 0.1)',
        textStyle: {
          color: '#1f2937'
        }
      },
      legend: {
        data: [
          locale === 'en' ? t('患者流量', 'Patient Flow') : '患者流量',
          locale === 'en' ? t('设备使用率', 'Device Utilization') : '设备使用率',
          locale === 'en' ? t('紧急呼叫', 'Emergency Calls') : '紧急呼叫'
        ],
        textStyle: {
          color: '#ffffff',
          fontSize: getScaledFontSizeNumber(16)
        },
        top: 35,
        show: true,
        type: 'scroll'
      },
      grid: {
        left: '8%',
        right: '8%',
        bottom: '8%',
        top: '25%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: hours,
        axisLine: {
          lineStyle: {
            color: '#ffffff'
          }
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: getScaledFontSizeNumber(12),
          interval: Math.max(1, Math.floor(hours.length / 8)) // 根据数据点数量动态调整间隔
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#ffffff'
          }
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: getScaledFontSizeNumber(14)
        },
        splitLine: {
          lineStyle: {
            color: '#ffffff'
          }
        }
      },
      series: [
        {
          name: locale === 'en' ? t('患者流量', 'Patient Flow') : '患者流量',
          type: 'line',
          smooth: true,
          connectNulls: false,
          data: patientFlow,
          itemStyle: {
            color: '#3b82f6'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(59, 130, 246, 0.3)' },
                { offset: 1, color: 'rgba(59, 130, 246, 0.05)' }
              ]
            }
          }
        },
        {
          name: locale === 'en' ? t('设备使用率', 'Device Utilization') : '设备使用率',
          type: 'line',
          smooth: true,
          connectNulls: false,
          data: deviceUsage,
          itemStyle: {
            color: '#10b981'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(16, 185, 129, 0.3)' },
                { offset: 1, color: 'rgba(16, 185, 129, 0.05)' }
              ]
            }
          }
        },
        {
          name: locale === 'en' ? t('紧急呼叫', 'Emergency Calls') : '紧急呼叫',
          type: 'line',
          smooth: true,
          connectNulls: false,
          data: emergencyCalls,
          itemStyle: {
            color: '#ef4444'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(239, 68, 68, 0.3)' },
                { offset: 1, color: 'rgba(239, 68, 68, 0.05)' }
              ]
            }
          }
        }
      ]
    }
  }, [t, locale])

  // 更新左侧图表（实时监控）
  const updateLeftChart = () => {
    if (!leftChartInstance.current) return
    leftChartInstance.current.setOption(generateRealTimeChartOption())
  }







  // 生成雷达图配置
  const generateRadarChartOption = useCallback(() => {
    return {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: 'rgba(0, 0, 0, 0.1)',
        textStyle: {
          color: '#1f2937'
        }
      },
      radar: {
        indicator: [
          { name: locale === 'en' ? t('CPU剩余', 'CPU Available') : 'CPU剩余', max: 100 },
          { name: locale === 'en' ? t('内存剩余', 'Memory Available') : '内存剩余', max: 100 },
          { name: locale === 'en' ? t('网络剩余', 'Network Available') : '网络剩余', max: 100 },
          { name: locale === 'en' ? t('存储剩余', 'Storage Available') : '存储剩余', max: 100 },
          { name: locale === 'en' ? t('GPU剩余', 'GPU Available') : 'GPU剩余', max: 100 }
        ],
        radius: '65%',
        center: ['50%', '60%'],
        axisName: {
          color: '#ffffff',
          fontSize: 13
        },
        splitLine: {
          lineStyle: {
            color: '#ffffff'
          }
        },
        splitArea: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#ffffff'
          }
        }
      },
      series: [
        {
          name: '剩余资源',
          type: 'radar',
          data: [
            {
              value: [
                45, // CPU剩余: 固定值
                60, // 内存剩余: 固定值
                70, // 网络剩余: 固定值
                75, // 存储剩余: 固定值
                50  // GPU剩余: 固定值
              ],
              name: '系统资源',
              itemStyle: {
                color: '#10b981'
              },
              areaStyle: {
                color: 'rgba(16, 185, 129, 0.3)'
              },
              lineStyle: {
                color: '#10b981',
                width: 2
              }
            }
          ]
        }
      ]
    }
  }, [t, locale])

  // 更新设备使用率雷达图
  const updateDeviceRadar = () => {
    if (!deviceRadarInstance.current) return
    deviceRadarInstance.current.setOption(generateRadarChartOption())
  }

  // 语言变化时重新渲染图表
  useEffect(() => {
    if (!chartsInitialized) return

    // 更新雷达图 - 强制重新初始化
    if (deviceRadarInstance.current) {
      deviceRadarInstance.current.dispose()
      deviceRadarInstance.current = echarts.init(deviceRadarRef.current)
      deviceRadarInstance.current.setOption(generateRadarChartOption())
    }

    // 更新左侧实时监控图表
    if (leftChartInstance.current) {
      leftChartInstance.current.dispose()
      leftChartInstance.current = echarts.init(leftChartRef.current)
      leftChartInstance.current.setOption(generateRealTimeChartOption())
    }


  }, [locale, chartsInitialized, generateRadarChartOption, generateRealTimeChartOption])




  // 生成饼图配置
  const generatePieChartOption = useCallback(() => {
    const departments = locale === 'en'
      ? [t('急诊科', 'Emergency'), t('心内科', 'Cardiology'), t('外科', 'Surgery'), t('儿科', 'Pediatrics'), t('妇产科', 'OB-GYN'), t('ICU', 'ICU'), t('手术室', 'Operating Room'), t('药房', 'Pharmacy')]
      : ['急诊科', '心内科', '外科', '儿科', '妇产科', 'ICU', '手术室', '药房']
    const patientCounts = departments.map((_, index) => 120 + index * 10) // 固定值

    return {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: 'rgba(0, 0, 0, 0.1)',
        textStyle: {
          color: '#1f2937'
        },
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        data: departments,
        orient: 'vertical',
        right: '8%',
        top: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 14
        },
        type: 'scroll'
      },
      series: [
        {
          name: locale === 'en' ? t('患者数量', 'Patient Count') : '患者数量',
          type: 'pie',
          radius: ['30%', '75%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: true,
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          emphasis: {
            label: {
              show: false
            },
            labelLine: {
              show: false
            }
          },
          data: departments.map((dept, index) => ({
            value: patientCounts[index],
            name: dept,
            itemStyle: {
              color: [
                '#3b82f6', '#10b981', '#f59e0b', '#ef4444',
                '#8b5cf6', '#06b6d4', '#84cc16', '#f97316'
              ][index % 8]
            }
          }))
        }
      ]
    }
  }, [t, locale])

  // 更新患者流向饼图
  const updatePatientFlowPie = () => {
    if (!patientFlowPieInstance.current) return
    patientFlowPieInstance.current.setOption(generatePieChartOption())
  }

  // 语言变化时更新饼图
  useEffect(() => {
    if (!chartsInitialized) return

    if (patientFlowPieInstance.current) {
      patientFlowPieInstance.current.dispose()
      patientFlowPieInstance.current = echarts.init(patientFlowPieRef.current)
      patientFlowPieInstance.current.setOption(generatePieChartOption())
    }
  }, [locale, chartsInitialized, generatePieChartOption])



  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'excellent': return 'bg-green-500'
      case 'good': return 'bg-blue-500'
      case 'warning': return 'bg-yellow-500'
      case 'critical': return 'bg-red-500'
      default: return 'bg-gray-500'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'excellent': return '优秀'
      case 'good': return '良好'
      case 'warning': return '警告'
      case 'critical': return '紧急'
      default: return '未知'
    }
  }

  // 获取趋势图标
  const getTrendIcon = (trend: number) => {
    if (trend > 0) return <IconTrendingUp className="w-4 h-4 text-green-500" />
    if (trend < 0) return <IconTrendingDown className="w-4 h-4 text-red-500" />
    return <IconActivity className="w-4 h-4 text-gray-500" />
  }

  // 获取指标图标
  const getMetricIcon = (key: string) => {
    switch (key) {
      case 'bedUtilization': return <IconBed className="w-4 h-4" />
      case 'patientFlow': return <IconUsers className="w-4 h-4" />
      case 'deviceEfficiency': return <IconActivity className="w-4 h-4" />
      case 'satisfaction': return <IconHeart className="w-4 h-4" />
      case 'emergencyResponse': return <IconBolt className="w-4 h-4" />
      case 'resourceUtilization': return <IconTarget className="w-4 h-4" />
      default: return <IconChartBar className="w-4 h-4" />
    }
  }

  // 获取指标名称
  const getMetricName = (key: string) => {
    switch (key) {
      case 'bedUtilization': return '病床使用率'
      case 'patientFlow': return '在院患者'
      case 'deviceEfficiency': return '设备效率'
      case 'satisfaction': return '患者满意度'
      case 'emergencyResponse': return '应急响应'
      case 'resourceUtilization': return '资源利用率'
      default: return key
    }
  }

  // 获取指标单位
  const getMetricUnit = (key: string) => {
    switch (key) {
      case 'bedUtilization': return '%'
      case 'patientFlow': return '人'
      case 'deviceEfficiency': return '%'
      case 'satisfaction': return '%'
      case 'emergencyResponse': return '%'
      case 'resourceUtilization': return '%'
      default: return ''
    }
  }

  // 全屏切换
  const toggleFullscreen = async () => {
    try {
      if (document.fullscreenElement) {
        await document.exitFullscreen()
        setIsFullscreen(false)
      } else {
        await document.documentElement.requestFullscreen()
        setIsFullscreen(true)
      }
    } catch (err) {
      console.error('全屏切换失败:', err)
    }
  }

  // 监听屏幕宽度变化
  useEffect(() => {
    const checkScreenWidth = () => {
      const width = window.innerWidth
      const wasNarrowScreen = isNarrowScreen
      const nowNarrowScreen = width < 1200

      setIsNarrowScreen(nowNarrowScreen)

      // 屏幕尺寸变化时，重新生成图表
      if (wasNarrowScreen !== nowNarrowScreen && chartsInitialized) {
        setTimeout(() => {
          // 重新初始化所有图表
          if (leftChartRef.current && leftChartInstance.current) {
            leftChartInstance.current.dispose()
            leftChartInstance.current = echarts.init(leftChartRef.current)
            leftChartInstance.current.setOption(generateRealTimeChartOption())
          }

          if (deviceRadarRef.current && deviceRadarInstance.current) {
            deviceRadarInstance.current.dispose()
            deviceRadarInstance.current = echarts.init(deviceRadarRef.current)
            deviceRadarInstance.current.setOption(generateRadarChartOption())
          }

          if (patientFlowPieRef.current && patientFlowPieInstance.current) {
            patientFlowPieInstance.current.dispose()
            patientFlowPieInstance.current = echarts.init(patientFlowPieRef.current)
            patientFlowPieInstance.current.setOption(generatePieChartOption())
          }
        }, 100)
      }
    }

    checkScreenWidth()
    window.addEventListener('resize', checkScreenWidth)
    return () => window.removeEventListener('resize', checkScreenWidth)
  }, [isNarrowScreen, chartsInitialized, generateRealTimeChartOption, generateRadarChartOption, generatePieChartOption])

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      const wasFullscreen = isFullscreen
      const nowFullscreen = !!document.fullscreenElement
      setIsFullscreen(nowFullscreen)

      // 全屏状态变化时，重新生成图表
      if (wasFullscreen !== nowFullscreen && chartsInitialized) {
        setTimeout(() => {
          // 重新初始化所有图表
          if (leftChartRef.current && leftChartInstance.current) {
            leftChartInstance.current.dispose()
            leftChartInstance.current = echarts.init(leftChartRef.current)
            leftChartInstance.current.setOption(generateRealTimeChartOption())
          }

          if (deviceRadarRef.current && deviceRadarInstance.current) {
            deviceRadarInstance.current.dispose()
            deviceRadarInstance.current = echarts.init(deviceRadarRef.current)
            deviceRadarInstance.current.setOption(generateRadarChartOption())
          }

          if (patientFlowPieRef.current && patientFlowPieInstance.current) {
            patientFlowPieInstance.current.dispose()
            patientFlowPieInstance.current = echarts.init(patientFlowPieRef.current)
            patientFlowPieInstance.current.setOption(generatePieChartOption())
          }
        }, 300)
      }
    }

    document.addEventListener('fullscreenchange', handleFullscreenChange)
    return () => document.removeEventListener('fullscreenchange', handleFullscreenChange)
  }, [isFullscreen, chartsInitialized, generateRealTimeChartOption, generateRadarChartOption, generatePieChartOption])

  // 初始化
  useEffect(() => {
    initCharts()

    // 从API加载站点数据
    const loadSitesFromAPI = async () => {
      try {
        const { hospitalAPI } = await import('@/lib/api/hospital')
        const response = await hospitalAPI.getSites({
          status: 'active',
          limit: 100
        })
        
        if (response?.success && response?.data?.sites) {
          const apiSites = response.data.sites.map((site: any) => ({
            id: site.siteId,
            name: site.name,
            center: [site.coordinates.longitude, site.coordinates.latitude] as [number, number],
            zoom: site.zoom || 16,
            address: site.address,
            district: site.district,
            city: site.city,
            province: site.province
          }))
          
          setSites(apiSites)
          
          // 加载当前选中的站点
          const savedCurrentSiteId = localStorage.getItem('current_site_id')
          if (savedCurrentSiteId && apiSites.find((s: any) => s.id === savedCurrentSiteId)) {
            setCurrentSiteId(savedCurrentSiteId)
          } else if (apiSites.length > 0) {
            // 如果没有保存的当前站点，选择第一个
            setCurrentSiteId(apiSites[0].id)
          }
        }
      } catch (apiError) {
        console.error('从API加载站点数据失败，回退到本地存储:', apiError)
        
        // API失败时回退到本地存储
        try {
          const savedSites = localStorage.getItem('hospital_sites')
          if (savedSites) {
            const parsedSites: HospitalSite[] = JSON.parse(savedSites)
            setSites(parsedSites)

            const savedCurrentSiteId = localStorage.getItem('current_site_id')
            if (savedCurrentSiteId && parsedSites.find(s => s.id === savedCurrentSiteId)) {
              setCurrentSiteId(savedCurrentSiteId)
            } else if (parsedSites.length > 0) {
              setCurrentSiteId(parsedSites[0].id)
            }
          }
        } catch (error) {
          console.error('从本地存储加载站点数据失败:', error)
          localStorage.removeItem('hospital_sites')
          localStorage.removeItem('current_site_id')
        }
      }
    }
    
    loadSitesFromAPI()

    // 添加一个小的延迟，确保ECharts实例有足够时间初始化
    const initialRenderTimer = setTimeout(() => {
      setChartsInitialized(true)

      // 直接加载数据
      loadRealData()
    }, 100); // 增加延迟到100毫秒，确保DOM完全准备好

    // 禁用自动刷新，避免数据变化
    // const interval = setInterval(() => {
    //   loadRealData(true) // 静默刷新
    // }, 30000) // 30秒刷新一次（与真实数据更新频率一致）

    return () => {
      clearTimeout(initialRenderTimer); // 在组件卸载时清除初始渲染的定时器
      // clearInterval(interval) // 已禁用定时器
    }
  }, [])

  // 更新当前选中的医院
  useEffect(() => {
    const site = sites.find(s => s.id === currentSiteId)
    setCurrentSite(site || sites[0] || null)
  }, [sites, currentSiteId])



  // 当图表初始化完成后，确保数据被渲染
  useEffect(() => {
    if (chartsInitialized) {
      // 图表已初始化，立即渲染数据
      loadRealData()
    }
  }, [chartsInitialized])

  // 更新图表
  useEffect(() => {
    const timer = setTimeout(() => {
      // 更新所有图表（大屏幕和小屏幕）
      updateAllCharts()
    }, 100)

    return () => clearTimeout(timer)
  }, [lastUpdate])

  // 统一的图表更新函数
  const updateAllCharts = useCallback(() => {
    // 更新所有图表
    updateLeftChart()
    updateDeviceRadar()
    updatePatientFlowPie()
  }, [])

  // 防抖版本的图表更新
  const debouncedUpdateAllCharts = useMemo(() => debounce(updateAllCharts, 150), [updateAllCharts, debounce])

  // 窗口大小变化时重新调整图表
  useEffect(() => {
    const handleResize = () => {
      // 调整大屏幕图表
      setTimeout(() => {
        leftChartInstance.current?.resize()
        deviceRadarInstance.current?.resize()
        patientFlowPieInstance.current?.resize()

        // 更新图表配置以适应新的缩放因子
        debouncedUpdateAllCharts()
      }, 100)
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [scaleFactor])

  // 监听缩放因子变化
  useEffect(() => {
    if (chartsInitialized) {
      // 清理缓存以应用新的缩放因子
      clearChartCache()
      updateAllCharts()
    }
  }, [scaleFactor, baseFontSize, chartsInitialized, clearChartCache, updateAllCharts])

  // 内存清理和性能监控
  useEffect(() => {
    const memoryCheckInterval = setInterval(() => {
      // 检查内存使用情况（如果支持）
      if ('memory' in performance && (performance as any).memory) {
        const memory = (performance as any).memory
        const memoryUsage = memory.usedJSHeapSize / memory.totalJSHeapSize

        // 如果内存使用超过80%，清理图表缓存
        if (memoryUsage > 0.8) {
          console.warn('High memory usage detected, clearing chart cache')
          clearChartCache()

          // 强制垃圾回收（如果可用）
          if ('gc' in window && typeof (window as any).gc === 'function') {
            (window as any).gc()
          }
        }
      }
    }, 30000) // 每30秒检查一次

    return () => clearInterval(memoryCheckInterval)
  }, [clearChartCache])

  // 组件卸载时清理图表实例，防止内存泄漏
  useEffect(() => {
    return () => {
      // 清理图表配置缓存
      clearChartCache()

      // 销毁大屏幕图表
      leftChartInstance.current?.dispose()
      deviceRadarInstance.current?.dispose()
      patientFlowPieInstance.current?.dispose()

      // 清空图表实例引用
      leftChartInstance.current = null
      deviceRadarInstance.current = null
      patientFlowPieInstance.current = null

      // 重置初始化状态
      setChartsInitialized(false)
    }
  }, [clearChartCache])

  // 监听路由变化，确保在页面重新进入时重新初始化
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (!document.hidden && !chartsInitialized) {
        // 页面重新可见且图表未初始化时，重新初始化
        setTimeout(() => {
          initCharts()
        }, 50)
      }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)
    return () => document.removeEventListener('visibilitychange', handleVisibilityChange)
  }, [chartsInitialized])

  return (
    <>

      {/* 数据刷新指示器 */}
      {isDataRefreshing && (
        <div className="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 bg-blue-500 text-white px-4 py-2 rounded-full shadow-lg">
          <div className="flex items-center space-x-2">
            <span className="text-sm font-medium">数据更新中...</span>
          </div>
        </div>
      )}

      <div className={`${isFullscreen || externalFullscreen ? 'fixed inset-0 z-50' : 'relative'} bg-gray-900 ${screenSize === 'sm' ? 'min-h-[100vh]' : 'min-h-screen'
        } w-full overflow-hidden`}>
        {/* 背景装饰 */}

        {/* 顶部控制栏 */}
        <div className="relative z-10 flex flex-col sm:flex-row items-start sm:items-center justify-between p-2 sm:p-4 gap-2 sm:gap-0">
          <div className="flex items-center space-x-2 sm:space-x-4 flex-shrink-0">
            <h1 className="text-lg sm:text-xl lg:text-2xl font-bold text-white leading-tight">医疗数字孪生可视化大屏</h1>
          </div>

          <div className="flex items-center space-x-2 sm:space-x-3 flex-wrap gap-1 sm:gap-0">
            <div className="text-white text-xs sm:text-sm hidden md:block">
              最后更新: {lastUpdate}
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={loadRealData}
              className="bg-white/20 border-white/30 text-white hover:bg-white/30 text-xs sm:text-sm px-2 sm:px-3"
            >
              <IconRefresh className="w-3 h-3 sm:w-4 sm:h-4 mr-0 sm:mr-1" />
              <span className="hidden sm:inline">刷新</span>
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={toggleFullscreen}
              className="bg-white/20 border-white/30 text-white hover:bg-white/30 text-xs sm:text-sm px-2 sm:px-3"
            >
              {isFullscreen ? (
                <>
                  <IconMinimize className="w-3 h-3 sm:w-4 sm:h-4 mr-0 sm:mr-1" />
                  <span className="hidden sm:inline">退出全屏</span>
                </>
              ) : (
                <>
                  <IconMaximize className="w-3 h-3 sm:w-4 sm:h-4 mr-0 sm:mr-1" />
                  <span className="hidden sm:inline">全屏</span>
                </>
              )}
            </Button>
          </div>
        </div>

        {/* 全屏地图背景 */}
        <div className="absolute inset-0 z-0">
          {currentSite ? (
            <HospitalMapViewer
              ref={mapViewerRef}
              amapKey={AMAP_KEY}
              center={poiIntent?.center || currentSite.center}
              zoom={poiIntent?.zoom || currentSite.zoom}
              enableLocationMonitor={true}
              apiBaseUrl={config.api.baseUrl}
              onMapClick={handleMapClick}
              onModelClick={handleModelClick}
              onUserLocationClick={(location) => {
                console.log('用户位置点击:', location)
                toast.info(`用户: ${location.username || location.userId}`, {
                  description: `部门: ${location.department || '访客'} | 精度: ${location.accuracy}m`
                })
              }}
              onLocationRequestClick={(request) => {
                console.log('位置请求点击:', request)
                toast.info(`位置请求: ${request.title}`, {
                  description: `类型: ${request.type} | 优先级: ${request.priority}`
                })
              }}
              onPOIClick={(poi: POIData) => {
                console.log('🎯 点击POI:', poi)
                // 用户位置：只展示详细信息，不弹删除
                if (poi.type === 'user') {
                  toast.info(`用户: ${poi.name}`, {
                    description: `楼层: ${poi.floor} | ${poi.description || '无描述'}`
                  })
                  return
                }

                // 其他POI：展示信息（删除改为通过管理入口执行）
                toast.info(`POI信息: ${poi.name} (${poi.type})`, {
                  description: `楼层: ${poi.floor} | ${poi.description || '无描述'}`
                })
              }}
              className="w-full h-full"
            />
          ) : (
            <div className="flex items-center justify-center h-full text-gray-600 bg-gray-100">
              <div className="text-center">
                <IconMap className="w-24 h-24 mx-auto mb-6 text-gray-400" />
                <div className="text-2xl font-medium mb-4">医疗空间数字孪生</div>
                <div className="text-lg">请添加医院站点开始使用</div>
              </div>
            </div>
          )}
        </div>

        {/* POI 管理按钮 - 右下角 */}
        {currentSite && (
          <div
            className="fixed bottom-4 right-4 z-[9999] space-y-2"
            style={{ pointerEvents: 'auto' }}
            onMouseEnter={() => console.log('🖱️ 鼠标进入按钮区域')}
            onMouseLeave={() => console.log('🖱️ 鼠标离开按钮区域')}
            onClick={() => console.log('🖱️ 点击按钮区域')}
          >
            {/* AI Advisor */}
            <Button
              onClick={() => setShowAdvisor(v => !v)}
              variant="outline"
              size="sm"
              className="bg-white/80 text-gray-900 border-2 border-white pointer-events-auto"
              style={{ pointerEvents: 'auto', zIndex: 10000 }}
            >
              {showAdvisor ? '关闭AI方案' : 'AI分析/方案'}
            </Button>

            {/* 在线用户（替换“状态 / 管理POI”按钮区域） */}
            <div ref={userPanelRef} className="fixed" style={{ left: userPanelPos.x, top: userPanelPos.y, zIndex: 9999 }}>
              <div className="bg-black/60 backdrop-blur-md border border-white/10 text-white rounded-lg shadow-lg w-72 max-h-80 overflow-y-auto pointer-events-auto">
              <div className="px-3 py-2 border-b border-white/10 flex items-center justify-between cursor-move select-none" onMouseDown={startDragUserPanel as any}>
                <div className="text-sm font-medium">在线用户</div>
                <div className="text-xs text-white/60">点击定位</div>
              </div>
              <ul className="divide-y divide-white/10">
                {(mapViewerRef.current?.getUserLocations?.() || []).slice(0, 30).map(u => (
                  <li key={u.userId} className="px-3 py-2 hover:bg-white/10 cursor-pointer" onClick={() => {
                    try {
                      if (!mapViewerRef.current) return
                      const target: [number, number] = [u.longitude, u.latitude]
                      mapViewerRef.current.flyTo(target, 18)
                    } catch {}
                  }}>
                    <div className="flex items-center justify-between gap-2">
                      <div className="truncate text-sm">{u.username || `用户${u.userId.slice(-4)}`}</div>
                      <div className="text-[11px] text-white/60 shrink-0">{u.longitude.toFixed(2)}, {u.latitude.toFixed(2)}</div>
                    </div>
                  </li>
                ))}
                {(!mapViewerRef.current?.getUserLocations?.() || mapViewerRef.current.getUserLocations().length === 0) && (
                  <li className="px-3 py-3 text-sm text-white/60">暂无在线用户</li>
                )}
              </ul>
              </div>
            </div>
          </div>
        )}

        {showAdvisor && (
          // Lazy import to keep UI responsive
          <React.Suspense>
            {/* eslint-disable-next-line @next/next/no-async-client-component */}
            {React.createElement(require('@/components/AIAdvisorPanel').default, { onClose: () => setShowAdvisor(false) })}
          </React.Suspense>
        )}

        {/* 移除重复的位置信息显示 - 已在左上角的选中位置弹框中显示 */}

        {/* 地图显示模式控制 - 顶部中间 */}
        <div className="absolute top-4 left-1/2 transform -translate-x-1/2 z-20">
          <div className="bg-white/10 backdrop-blur-md rounded-lg border border-white/20 p-2">
            <div className="flex gap-1">
              <Button
                size="sm"
                variant={mapDisplayMode === 'overview' ? 'default' : 'ghost'}
                onClick={() => setMapDisplayMode('overview')}
                className={`text-xs h-7 px-2 pointer-events-auto text-white hover:bg-white/20 ${mapDisplayMode === 'overview' ? 'bg-blue-500/60' : ''
                  }`}
              >
                🏥 概览
              </Button>
              <Button
                size="sm"
                variant={mapDisplayMode === 'departments' ? 'default' : 'ghost'}
                onClick={() => setMapDisplayMode('departments')}
                className={`text-xs h-7 px-2 pointer-events-auto text-white hover:bg-white/20 ${mapDisplayMode === 'departments' ? 'bg-blue-500/60' : ''
                  }`}
              >
                🏥 科室
              </Button>
              <Button
                size="sm"
                variant={mapDisplayMode === 'equipment' ? 'default' : 'ghost'}
                onClick={() => setMapDisplayMode('equipment')}
                className={`text-xs h-7 px-2 pointer-events-auto text-white hover:bg-white/20 ${mapDisplayMode === 'equipment' ? 'bg-blue-500/60' : ''
                  }`}
              >
                🔬 设备
              </Button>
              <Button
                size="sm"
                variant={mapDisplayMode === 'alerts' ? 'default' : 'ghost'}
                onClick={() => setMapDisplayMode('alerts')}
                className={`text-xs h-7 px-2 pointer-events-auto text-white hover:bg-white/20 ${mapDisplayMode === 'alerts' ? 'bg-blue-500/60' : ''
                  }`}
              >
                ⚠️ 告警
              </Button>
            </div>
          </div>
        </div>



        {/* 浮动面板区域 */}
        <div className="relative z-20 h-[calc(100vh-80px)] sm:h-[calc(100vh-120px)] pointer-events-none p-2 sm:p-4">
          {isNarrowScreen ? (
            /* 窄屏幕布局 - 所有图表左侧纵向排列 */
            <div className="absolute left-0 top-0 w-[400px] min-w-[400px] h-full overflow-y-auto pointer-events-auto">
              <div className="flex flex-col space-y-4 p-4">
                {/* 医院站点管理 */}
                <div className="h-[250px] min-h-[250px]">
                  <HospitalSiteManager
                    sites={sites}
                    onSitesChange={handleSitesChange}
                    currentSiteId={currentSiteId}
                    onSiteSelect={handleSiteSelect}
                    className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover h-full"
                  />
                </div>

                {/* 设备使用率 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover overflow-hidden group hover:scale-[1.02] transition-all duration-300 h-[350px] min-h-[350px]">
                  <CardHeader className="pb-2 sm:pb-3">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm lg:text-base">
                        <div className="p-1 sm:p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-400/30">
                          <IconGauge className="w-3 h-3 sm:w-4 sm:h-4 text-yellow-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">设备使用率</span>
                      </span>
                      <div className="flex items-center gap-1 sm:gap-2">
                        <span className="text-xs text-white/60 hidden sm:inline">监控中</span>
                        <div className={`w-2 h-2 rounded-full bg-yellow-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1">
                    <div ref={deviceRadarRef} className="w-full h-full" />
                  </CardContent>
                </Card>

                {/* 实时监控 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover overflow-hidden group hover:scale-[1.02] transition-all duration-300 h-[450px] min-h-[450px]">
                  <CardHeader className="pt-3 pb-2 sm:pb-3">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm lg:text-base">
                        <div className="p-1 sm:p-1.5 rounded-lg bg-blue-500/20 border border-blue-400/30">
                          <IconChartBar className="w-3 h-3 sm:w-4 sm:h-4 text-blue-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">实时监控</span>
                      </span>
                      <div className="flex items-center gap-1 sm:gap-2">
                        <span className="text-xs text-white/60 hidden sm:inline">实时</span>
                        <div className={`w-2 h-2 rounded-full bg-green-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1">
                    <div ref={leftChartRef} className="w-full h-full" />
                  </CardContent>
                </Card>

                {/* 患者流向 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover group hover:scale-[1.02] transition-all duration-300 h-[350px] min-h-[350px]">
                  <CardHeader className="pb-1 sm:pb-2">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm">
                        <div className="p-1 rounded-lg bg-purple-500/20 border border-purple-400/30">
                          <IconUsers className="w-3 h-3 text-purple-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">患者流向</span>
                      </span>
                      <div className="flex items-center gap-1">
                        <div className={`w-2 h-2 rounded-full bg-purple-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1 min-h-0">
                    <div ref={patientFlowPieRef} className="w-full h-full" />
                  </CardContent>
                </Card>
              </div>
            </div>
          ) : (
            /* 宽屏幕布局 - 左右两侧分布 */
            <>
              {/* 左侧图表区域 - 占23%宽度，垂直排列 */}
              <div className="absolute left-0 top-0 w-[23%] min-w-[350px] h-[95%] p-4 flex flex-col space-y-4 pointer-events-auto">
                {/* 医院站点管理 */}
                <div className="flex-1">
                  <HospitalSiteManager
                    sites={sites}
                    onSitesChange={handleSitesChange}
                    currentSiteId={currentSiteId}
                    onSiteSelect={handleSiteSelect}
                    className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover h-full"
                  />
                </div>

                {/* 设备使用率 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover overflow-hidden group hover:scale-[1.02] transition-all duration-300 flex-1">
                  <CardHeader className="pb-2 sm:pb-3">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm lg:text-base">
                        <div className="p-1 sm:p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-400/30">
                          <IconGauge className="w-3 h-3 sm:w-4 sm:h-4 text-yellow-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">设备使用率</span>
                      </span>
                      <div className="flex items-center gap-1 sm:gap-2">
                        <span className="text-xs text-white/60 hidden sm:inline">监控中</span>
                        <div className={`w-2 h-2 rounded-full bg-yellow-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1">
                    <div ref={deviceRadarRef} className="w-full h-full" />
                  </CardContent>
                </Card>
              </div>

              {/* 右侧图表区域 - 占23%宽度，垂直排列 */}
              <div className="absolute right-0 top-0 w-[23%] min-w-[350px] h-[95%] p-4 flex flex-col space-y-4 pointer-events-auto">
                {/* 实时监控 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover overflow-hidden group hover:scale-[1.02] transition-all duration-300 flex-[2]">
                  <CardHeader className="pt-3 pb-2 sm:pb-3">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm lg:text-base">
                        <div className="p-1 sm:p-1.5 rounded-lg bg-blue-500/20 border border-blue-400/30">
                          <IconChartBar className="w-3 h-3 sm:w-4 sm:h-4 text-blue-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">实时监控</span>
                      </span>
                      <div className="flex items-center gap-1 sm:gap-2">
                        <span className="text-xs text-white/60 hidden sm:inline">实时</span>
                        <div className={`w-2 h-2 rounded-full bg-green-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1">
                    <div ref={leftChartRef} className="w-full h-full" />
                  </CardContent>
                </Card>

                {/* 患者流向 */}
                <Card className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-xl shadow-lg shadow-black/10 modern-shadow-hover group hover:scale-[1.02] transition-all duration-300 flex-1">
                  <CardHeader className="pb-1 sm:pb-2">
                    <CardTitle className="text-white flex items-center justify-between">
                      <span className="flex items-center text-xs sm:text-sm">
                        <div className="p-1 rounded-lg bg-purple-500/20 border border-purple-400/30">
                          <IconUsers className="w-3 h-3 text-purple-300" />
                        </div>
                        <span className="ml-1 sm:ml-2">患者流向</span>
                      </span>
                      <div className="flex items-center gap-1">
                        <div className={`w-2 h-2 rounded-full bg-purple-500 `}></div>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0 flex-1 min-h-0">
                    <div ref={patientFlowPieRef} className="w-full h-full" />
                  </CardContent>
                </Card>
              </div>
            </>
          )}

          {/* 顶部中央 - 医院信息显示 */}
          {currentSite && (
            <div className="absolute top-20 left-1/2 transform -translate-x-1/2 pointer-events-auto hidden md:block z-10">
              <div className="flex items-center gap-2 sm:gap-3 backdrop-blur-xl bg-black/30 border border-white/20 rounded-xl px-3 sm:px-4 py-1.5 sm:py-2">
                <div className="text-white flex items-center gap-1 sm:gap-2">
                  <IconMap className="w-3 h-3 sm:w-4 sm:h-4 text-green-400" />
                  <span className="font-medium text-xs sm:text-sm lg:text-base">{currentSite.name}</span>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    console.log('强制刷新地图定位:', currentSite)
                    setCurrentSite({ ...currentSite })
                    toast.info('正在刷新地图定位...')
                  }}
                  className="h-6 sm:h-7 px-2 sm:px-3 bg-white/10 border-white/20 text-white hover:bg-white/20 text-xs"
                >
                  <IconRefresh className="w-3 h-3 sm:w-4 sm:h-4 mr-0 sm:mr-1" />
                  <span className="hidden lg:inline">刷新定位</span>
                </Button>
              </div>
            </div>
          )}



          {/* 选中位置信息 */}
          {selectedPosition && currentSite && (
            <div className="absolute top-32 left-4 pointer-events-auto z-20">
              <div className="bg-black/80 backdrop-blur text-white p-3 rounded-lg text-xs border border-white/20">
                <div className="font-medium mb-1 flex items-center gap-2">
                  <IconTarget className="w-3 h-3" />
                  选中位置
                </div>
                <div>经度: {selectedPosition[0].toFixed(6)}</div>
                <div>纬度: {selectedPosition[1].toFixed(6)}</div>
                <div>高度: {selectedPosition[2].toFixed(2)}m</div>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setSelectedPosition(null)}
                  className="mt-2 h-6 px-2 text-xs text-white hover:bg-white/20"
                >
                  关闭
                </Button>
              </div>
            </div>
          )}
        </div>

        {/* 底部状态栏 - 浮动显示 */}
        <div className="absolute bottom-0 left-0 right-0 z-30 p-4">
          <div className="flex items-center justify-center">
            <div className="backdrop-blur-xl bg-black/30 border border-white/20 rounded-xl px-6 py-2 flex items-center space-x-8 text-white/80 text-sm">
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-500 rounded-full "></div>
                <span>系统运行正常</span>
              </div>
              <div className="flex items-center space-x-2">
                <IconGauge className="w-4 h-4" />
                <span>CPU: 45% | 内存: 62%</span>
              </div>
              <div className="flex items-center space-x-2">
                <IconActivity className="w-4 h-4" />
                <span>网络延迟: 12ms</span>
              </div>
              <div className="flex items-center space-x-2">
                <IconShield className="w-4 h-4" />
                <span>安全等级: 高</span>
              </div>
              <div className="flex items-center space-x-2">
                <IconActivity className="w-4 h-4" />
                <span>数据同步: 正常</span>
              </div>
            </div>
          </div>
        </div>
        {/* 移动端底部操作栏 */}
        <div className="absolute bottom-0 left-0 right-0 z-30 sm:hidden">
          <div className="bg-black/80 backdrop-blur-xl border-t border-white/20 px-4 py-2">
            <div className="flex items-center justify-between text-white">
              <div className="flex items-center space-x-4">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={loadRealData}
                  className="bg-white/10 hover:bg-white/20 text-white border-white/20 px-3 py-2"
                >
                  <IconRefresh className="w-4 h-4" />
                </Button>
              </div>
              {currentSite && (
                <div className="flex items-center space-x-2 text-sm">
                  <IconMap className="w-4 h-4 text-green-400" />
                  <span>{currentSite.name}</span>
                </div>
              )}
              <div className="text-xs text-white/60">
                {new Date().toLocaleTimeString()}
              </div>
            </div>
          </div>
        </div>

        {/* POI 添加弹框 */}
        {(() => {
          console.log('🔍 弹框渲染检查 - showAddPOI:', showAddPOI)
          return showAddPOI
        })() && (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={(e) => {
              if (e.target === e.currentTarget) {
                console.log('🎯 点击背景关闭弹框')
                setShowAddPOI(false)
              }
            }}>
              <div className="bg-white rounded-lg shadow-xl w-96 max-w-full mx-4">
                <div className="p-6">
                  <h3 className="text-lg font-semibold mb-4">添加POI点位</h3>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="poi-name">名称</Label>
                      <Input
                        id="poi-name"
                        value={poiForm.name}
                        onChange={(e) => setPOIForm(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="输入POI名称"
                      />
                    </div>

                    <div>
                      <Label htmlFor="poi-type">类型</Label>
                      <Select
                        value={poiForm.type}
                        onValueChange={(value) => setPOIForm(prev => ({ ...prev, type: value as POIData['type'] }))}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {Object.entries(config.hospital.poiTypes).map(([value, label]) => (
                            <SelectItem key={value} value={value}>
                              {label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <Label htmlFor="poi-floor">楼层</Label>
                      <Select
                        value={poiForm.floor}
                        onValueChange={(value) => setPOIForm(prev => ({ ...prev, floor: value }))}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {config.hospital.defaultFloors.map((floor) => (
                            <SelectItem key={floor} value={floor}>
                              {floor}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <Label htmlFor="poi-description">描述</Label>
                      <Input
                        id="poi-description"
                        value={poiForm.description}
                        onChange={(e) => setPOIForm(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="输入描述信息（可选）"
                      />
                    </div>

                    <div className="flex justify-end space-x-2 pt-4">
                      <Button
                        variant="outline"
                        onClick={() => setShowAddPOI(false)}
                      >
                        取消
                      </Button>
                      <Button onClick={async () => {
                        if (!selectedPosition && !selectedModel) {
                          toast.error('请先在地图上选择位置')
                          return
                        }

                        try {
                          const position: [number, number] = selectedPosition
                            ? [selectedPosition[0], selectedPosition[1]]
                            : [0, 0]

                          const newPOI: POIData = {
                            id: `poi_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                            name: poiForm.name,
                            type: poiForm.type,
                            position,
                            floor: poiForm.floor,
                            description: poiForm.description
                          }

                          // 注册到POI目录
                          poiCatalog.registerPOI(newPOI)

                          // 保存到数据库
                          try {
                            await hospitalDB.addPOI({
                              hospitalId: 'default_hospital',
                              floorId: poiForm.floor,
                              name: poiForm.name,
                              type: poiForm.type,
                              position,
                              description: poiForm.description,
                              status: 'active',
                              metadata: {
                                addedFrom: selectedModel ? 'model' : 'map',
                                modelObject: selectedModel?.object?.name
                              }
                            })
                          } catch (dbError) {
                            console.warn('数据库保存失败:', dbError)
                          }

                          setPOIs(prev => [...prev, newPOI])

                          // 直接添加到地图
                          if (mapViewerRef.current) {
                            mapViewerRef.current.addPOI(newPOI)
                          }

                          setPOIForm({
                            name: '',
                            type: 'department',
                            floor: 'L1',
                            description: ''
                          })
                          setShowAddPOI(false)
                          setSelectedPosition(null)
                          setSelectedModel(null)

                          toast.success('POI添加成功', {
                            description: `POI ID: ${newPOI.id}`,
                            action: {
                              label: '复制分享链接',
                              onClick: () => {
                                const shareUrl = `${window.location.origin}/dashboard?poiIds=${newPOI.id}&zoom=18`
                                navigator.clipboard.writeText(shareUrl)
                                toast.success('分享链接已复制到剪贴板')
                              }
                            }
                          })
                        } catch (error) {
                          console.error('添加POI失败:', error)
                          toast.error('添加POI失败')
                        }
                      }}>
                        添加
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
      </div>
    </>
  )
}
